package com.linux.huhx.thread;

import java.util.concurrent.TimeUnit;

/**
 * Created by huhx on 2017-05-24.
 */
public class ThreadJoinTest {
    public static void main(String[] args) {
        JsonThread jsonThread = new JsonThread("json");
        jsonThread.start();
        try {
            jsonThread.joinMe();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        JsonTest2 jsonTest2 = new JsonTest2(jsonThread);
//        jsonTest2.start();
        for (int i = 0; i < 5; i++) {
            System.out.println("in main thread " + i);
        }
    }
}

class JsonThread extends Thread {

    public JsonThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
                System.out.println("hello i = " + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public final synchronized void joinMe() throws InterruptedException {
        while (isAlive()) {
            System.out.println("hello world");
            wait(0);
        }
        System.out.println("the thread name: " + Thread.currentThread().getName()); // main
        System.out.println("the thread state: " + Thread.currentThread().getState()); // RUNNING
        System.out.println("the thread name: " + this.getName()); // json
        System.out.println("the thread state: " + this.getState()); // TERMINATED
    }
}

class JsonTest2 extends Thread {
    JsonThread thread = null;

    public JsonTest2(JsonThread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
        try {
            thread.joinMe();
            for (int i = 0; i < 5; i++) {
                TimeUnit.MILLISECONDS.sleep(1000);
                System.out.println("world i = " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
